package com.zhm.demo.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

public class CmdUtil {

    public static Object evalVal(String language, Map<String, Object> param, String eval) {
        List<String> cmd = new ArrayList<>();
        cmd.add("D:\\PycharmProjects\\fastApiProject\\.venv\\Scripts\\python.exe");
        cmd.add(eval);
        param.forEach((k, v) -> {
            cmd.add(k + "=" + v);
        });
        List<String> resList = new ArrayList<>();
        try {
            // Python 脚本路径
            ProcessBuilder pb = new ProcessBuilder(cmd);

            // 启动进程并获取其输出
            Process process = pb.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String line = "";
            while ((line = reader.readLine()) != null) {
                // 输出 Python 脚本的返回值
                System.out.println("return ========== :  " + line);
                resList.add(line);
            }

            process.waitFor(); // 等待进程执行完成
            reader.close();
        } catch (Exception e) {
            throw new RuntimeException("调用python脚本获取设备token失败", e);
        }
        return resList.get(resList.size() - 1);
    }

    public static void main(String[] args) {

        Map<String, Object> param = new HashMap<>();
        param.put("a", "123");
        param.put("b", "123");
        Object o = evalVal("python", param, "D:\\PycharmProjects\\fastApiProject\\test.py");
        System.out.println(o);
    }
}
